﻿/**
 * The AudioTrack Library by Chris J. Rock. Aug 10, 2011
 * Check out chrisjrock.net and be a king among men.
 *
 * Copyright (c) 2011 Chris J. Rock
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/


package net.chrisjrock.sound.audioTrack.track 
{
	import flash.events.EventDispatcher;
	import flash.media.SoundTransform;
	
	import net.chrisjrock.sound.audioTrack.data.IAudioMixerData;
	import net.chrisjrock.sound.audioTrack.data.IAudioTrackData;
	import net.chrisjrock.sound.audioTrack.events.AudioMixerEvent;
	import net.chrisjrock.sound.audioTrack.events.AudioTrackEvent;
	import net.chrisjrock.sound.audioTrack.mixer.IAudioMixer;
	
	/**
	 * An abstract super class that handles all basic track functionality.
	 * @author Christopher J. Rock
	 */
	
	public class AbstractTrack extends EventDispatcher implements IAudioTrack
	{
		private var _trackId:String;
		
		private var _mixer:IAudioMixer;
		
		protected var _mute:Boolean;
		private var _solo:Boolean;
		
		protected var _effect:IAudioTrackData;
		
		private var _pan:Number;
		private var _volume:Number;
		
		/*
		Commented out advanced panning so it can be perfected later. Not a very important feature anyway.
		private var _leftToLeft:Number;
		private var _leftToRight:Number;
		private var _rightToLeft:Number;
		private var _rightToRight:Number;*/
		/*private var _panRule:Number;
		private var _angle:Number;
		private var _distance:Number;
		private var _interauralDis:Number;
		private var _interauralTimeDiff:Number; //For humans this is .63ms.
		private var _interauralAmplitudeDiff:Number;*/
		//TODO: Study HRTF--Head related transfer function
		
		private var _autoUpdateTransform:Boolean = true;
		
		public function AbstractTrack(trackId:String) 
		{
			_trackId = trackId;
			_pan = 0;
			_volume = 1;
			
			/*_leftToLeft = 1;
			_leftToRight = 0;
			_rightToLeft = 0;
			_rightToRight = 1;
			_panRule = 0;
			_angle = -90;
			_distance = 1;
			_interauralDis = 1;*/
			
			_effect = instantiateTrackData();
		}
		
		/**
		 * @inheritDoc
		 */
		public function dispose():void 
		{
			//Uses the public setters so the track will be properly removed from its mixer.
			mixer = null;
		}
		
		/**
		 * @inheritDoc
		 */
		public function cloneData ():IAudioTrackData
		{
			var trackData:IAudioTrackData = instantiateTrackData();
			trackData.volume = _volume;
			trackData.pan = _pan;
			trackData.mute = _mute;
			trackData.solo = _solo;
			return trackData;
		}
		
		/**
		 * @inheritDoc
		 */
		public function updateTransform (transform:SoundTransform = null /*, panRule:Number = NaN*/):void 
		{
			if (transform) 
			{
				_pan = transform.pan;
				_volume = transform.volume;
				
				/*
				if (!isNaN(panRule))
				{
					_panRule = transform.panRule;
				}
				
				_leftToLeft = transform.leftToLeft;
				_leftToRight = transform.leftToRight;
				_rightToLeft = transform.rightToLeft;
				_rightToRight = transform.rightToRight;
				*/
			}
		}
		
		/*public function setPolar (angle:Number , distance:Number):Number 
		{
			_leftToLeft =
			_angle = angle;
			return _angle;
		}*/
		
		/**
		 * @inheritDoc
		 */
		public function getTransform ():SoundTransform 
		{
			var transform:SoundTransform = new SoundTransform();
			applyTrackEffectToTransform(transform);
			applyMixerEffectToTransform(transform);
			return transform;
		}
		
		/**
		 * Apply the effect data of the track to a SoundTransform.
		 */
		protected function applyTrackEffectToTransform (transform:SoundTransform):void
		{
			transform.volume = _effect.volume;// - _panRule * (1 - panAbs);
			transform.pan = _effect.pan;
			/*transform.leftToLeft = _leftToLeft;
			transform.leftToRight = _leftToRight;
			transform.rightToLeft = _rightToLeft;
			transform.rightToRight = _rightToRight;*/
		}
		
		/**
		 * Apply the inherited effect data of the parent mixer to a SoundTransform.
		 */
		protected function applyMixerEffectToTransform (transform:SoundTransform):void
		{
			if (_effect.mute)
			{
				transform.volume = 0;
			}
			else if (_mixer && _mixer.effect)
			{
				var inheritance:IAudioMixerData = IAudioMixerData(_mixer.effect);
				if (inheritance.soloTrack != null && inheritance.soloTrack != this)
				{
					transform.volume = 0;
				}
			}
		}
		
		/**
		 * Updates effect data and applies it to the track.
		 */
		protected function updateEffect(inheritSolo:Boolean = true):void 
		{
			_effect = instantiateTrackData();
			refreshEffectData(inheritSolo);
			
			if (_autoUpdateTransform)
			{
				applyEffect();
			}
		}
		
		/**
		 * Returns a new instance of an IAudioTrackData implementation appropriate for the given subclass of AbstractTrack.
		 */
		protected function instantiateTrackData ():IAudioTrackData
		{
			throw (new Error("This is a virtual method and must be overridden."));
		}
		
		/**
		 * Updates the effect object so that it represents a concatenation of the current data of the track and the parent mixer.
		 */
		protected function refreshEffectData (inheritSolo:Boolean = true):void
		{
			_effect.volume = _volume;
			_effect.pan = _pan;
			_effect.mute = _mute;
			
			_effect.solo = _solo;
			
			if (_mixer == null || _mixer.effect == null)
			{
				return;
			}
			
			var inheritance:IAudioMixerData = IAudioMixerData(_mixer.effect);
			
			_effect.volume *= inheritance.volume;
			_effect.pan += inheritance.pan; //TODO: Make this more sophisticated.
			
			if (!_effect.mute)
			{
				_effect.mute = inheritance.mute;
			}
			
			if (inheritSolo && inheritance.soloTrack != this) 
			{
				_effect.solo = false;
			}
		}
		
		/**
		 * Applies current effect data to the track's sound.
		 */
		protected function applyEffect ():void
		{
			throw (new Error("This is a virtual method and must be overridden."));
		}
		
		/**
		 * This method must be called whenever solo status is modified.
		 */
		protected function updateSolo ():void
		{
			dispatchEvent(new AudioTrackEvent(AudioTrackEvent.SOLO_TOGGLE));
		}
		
		/**
		 * Removes the effects of the current mixer.
		 */
		private function removeMixer ():void
		{
			if (_mixer) 
			{
				var mixer:IAudioMixer = _mixer;
				_mixer = null;
				mixer.removeEventListener(AudioMixerEvent.UPDATE , mixerEventHandler);
				if (mixer.hasTrack(this))
				{
					mixer.removeTrack(this);
				}
				updateEffect();
			}
		}
		
		/**
		 * Applies the effects of the current mixer.
		 */
		private function applyMixer ():void
		{
			if (_mixer) 
			{
				_mixer.addEventListener(AudioMixerEvent.UPDATE , mixerEventHandler);
				_mixer.addTrack(this);
				updateEffect();
			}
		}
		
		/**
		 * Handles events from the parent mixer.
		 */
		private function mixerEventHandler (event:AudioMixerEvent):void
		{
			updateEffect();
		}
		
		/**
		 * @inheritDoc
		 */
		public function get trackId():String
		{
			return _trackId;
		}
		
		public function set trackId(value:String):void
		{
			_trackId = value;
		}
		
		/**
		 * @inheritDoc
		 */
		public function get mixer ():IAudioMixer
		{
			return _mixer;
		}
		
		public function set mixer (value:IAudioMixer):void 
		{
			if (value != _mixer)
			{
				removeMixer();
				_mixer = value;
				applyMixer();
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function get mute ():Boolean
		{
			return _mute;
		}
		
		public function set mute (value:Boolean):void 
		{
			if (_mute != value) 
			{
				_mute = value;
				updateEffect();
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.MUTE_TOGGLE));
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function get solo ():Boolean
		{
			return _solo;
		}
		
		public function set solo (value:Boolean):void 
		{
			if (_solo != value) 
			{
				_solo = value;
				updateSolo();
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function get effect ():IAudioTrackData
		{
			return _effect.cloneData();
		}
		
		/**
		 * @inheritDoc
		 */
		public function get pan ():Number
		{
			return _pan;
		}
		
		public function set pan (value:Number):void 
		{
			_pan = value;
			updateEffect();
		}
		
		/**
		 * @inheritDoc
		 */
		public function get volume ():Number
		{
			return _volume;
		}
		
		public function set volume (value:Number):void 
		{
			_volume = value;
			updateEffect();
		}
		
		/*public function get panRule ():Number
		{
		return _panRule;
		}
		
		public function set panRule (value:Number):void 
		{
		_panRule = value;
		if (_autoUpdateTransform)
		{
		updateTransform();
		}
		}
		
		public function get angle ():Number
		{
		return _angle;
		}
		
		public function get leftToLeft ():Number
		{
		return _leftToLeft;
		}
		
		public function set leftToLeft (value:Number):void 
		{
		_leftToLeft = value;
		if (_autoUpdateTransform)
		{
		updateTransform();
		}
		}
		
		public function get leftToRight ():Number
		{
		return _leftToRight;
		}
		
		public function set leftToRight (value:Number):void 
		{
		_leftToRight = value;
		if (_autoUpdateTransform)
		{
		updateTransform();
		}
		}
		
		public function get rightToLeft ():Number
		{
		return _rightToLeft;
		}
		
		public function set rightToLeft (value:Number):void 
		{
		_rightToLeft = value;
		if (_autoUpdateTransform)
		{
		updateTransform();
		}
		}
		
		public function get rightToRight ():Number
		{
		return _rightToRight;
		}
		
		public function set rightToRight (value:Number):void 
		{
		_rightToRight = value;
		if (_autoUpdateTransform)
		{
		updateTransform();
		}
		}*/
		
		/**
		 * Determines whether or not the track's transform will be automatically update when changes are made to effect data.
		 */
		public function get autoUpdateTransform():Boolean
		{
			return _autoUpdateTransform;
		}
		
		/**
		 * @private
		 */
		public function set autoUpdateTransform(value:Boolean):void
		{
			_autoUpdateTransform = value;
		}

	}
	
}